"""
Module to simulate the G711 compression

Functions
---------
`alaw_compression`: Compress a signal by using the G711 A-law algorithm.

`alaw_expand`: Expands a G711 A-law compressed signal .

"""
#
# g711.py
#
# Copyright (C) 2012 Robert Buj Gelonch
# Copyright (C) 2012 David Megias Jimenez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
__author__ = "Robert Buj Gelonch, and David Megias Jimenez"
__copyright__ = "Copyright 2012, Robert Buj Gelonch and David Megias Jimenez"
__credits__ = ["Robert Buj Gelonch", "David Megias Jimenez"]
__license__ = "GPL"
__version__ = "3"
__maintainer__ = "Robert Buj"
__email__ = "rbuj@uoc.edu"
__status__ = "Development"
__docformat__ = 'plaintext'

import numpy

# S = signed signal of 13-bit
def alaw_compression(S):
    mantissa_len = 4
    mantissa = numpy.zeros(len(S), dtype=int)
    exponent = numpy.zeros(len(S), dtype=int)
    signal = numpy.array(S)
    aux = signal.astype(numpy.int16)
    for i in range(len(S)):
        if abs(signal[i]) > 2 ** 5:
            MSB = int(numpy.log2(abs(signal[i]))) + 1
            exponent[i] = MSB - 1 - mantissa_len
            mantissa[i] = (abs(aux[i]) - 2 ** (MSB-1)) >> exponent[i]
        else:
            exponent[i] = 0
            mantissa[i] = abs(aux[i]) >> 1
    sign = numpy.sign(S)
    return (mantissa, exponent, sign)

def alaw_expand(mantissa, exponent, sign):
    mantissa_len = 4
    R = numpy.zeros(len(mantissa), dtype=int)
    for i in range(len(R)):
        if exponent[i] == 0:
            R[i] = mantissa[i] << 1
        else:
            R[i] = mantissa[i] << exponent[i]
            R[i] = R[i] + (2 ** (exponent[i] + mantissa_len))
    R = numpy.copysign(R, sign)
    return R.astype(numpy.int16)
